package com.benson.common.creator.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.benson.common.creator.entity.Creator;
import com.benson.common.creator.entity.CreatorDataSource;
import com.benson.common.creator.mapper.CreatorDao;
import com.benson.common.creator.service.ICreatorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 代码生成 服务实现类
 * </p>
 *
 * @author zhangby
 * @since 2020-02-18
 */
@Service
public class CreatorServiceImpl extends ServiceImpl<CreatorDao, Creator> implements ICreatorService {

    @Autowired
    CreatorDataSource dataSource;

    /**
     * 代码生成
     * @param id id
     */
    @Override
    public void generator(String id) throws FileNotFoundException {
        Creator creator = getById(id);

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = creator.getOutPutDir();
        // 设置存储路径
        if (projectPath.replace("/src/main/java","").length() == 0) {
            projectPath = ResourceUtils.getURL("classpath:").getPath().replace("/target/classes","")+"/src/main/java";
        }
        gc.setOutputDir(projectPath);
        gc.setAuthor(creator.getAuthor());
        gc.setOpen(false);
        gc.setActiveRecord(true);
        gc.setSwagger2(true);
        gc.setXmlName(null);
        gc.setFileOverride(true);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setMapperName("%sDao");
        mpg.setGlobalConfig(gc);


        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dataSource.getUrl());
        dsc.setDriverName(dataSource.getDriverClassName());
        dsc.setUsername(dataSource.getUsername());
        dsc.setPassword(dataSource.getPassword());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(creator.getPackageDir());
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 velocity
        String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        String path = projectPath;
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                String dirPath = path.replace("/src/main/java", "") + "/src/main/resources/mapper";
                //
                File file = new File(dirPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                return  dirPath + "/" + tableInfo.getEntityName() + "Dao" + StringPool.DOT_XML;
            }
        });

        //创建
        cfg.setFileCreate((configBuilder, fileType, filePath)-> {
            /** 配置指定生成文件 */
            List<FileType> createList = Stream.of(creator.getCreateFile().split(","))
                    .map(FileType::valueOf)
                    .collect(Collectors.toList());
            /** 生成文件 */
            return createList.contains(fileType)?true:false;
        });


        cfg.setFileOutConfigList(focList);

        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        templateConfig.setXml(null);
        templateConfig.setEntity("/templates/generator/entity.java.vm");
        templateConfig.setMapper("/templates/generator/mapper.java.vm");
        mpg.setTemplate(templateConfig);

        String baseEntity = Optional.ofNullable(creator.getBaseEntity())
                .filter(StrUtil::isNotBlank)
                .orElse(null);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // 设置基础类
        if (ObjectUtil.isNotNull(baseEntity)) {
            strategy.setSuperEntityClass(baseEntity);
        }
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(creator.getTableName().split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(creator.getTablePrefix().split(","));
        mpg.setStrategy(strategy);
        mpg.execute();
    }
}
